package com.pine.sunshineelder;

import java.lang.invoke.MethodHandles;
import java.util.EnumSet;
import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.validation.Validation;
import javax.validation.Validator;
import org.hibernate.validator.HibernateValidator;
import org.slf4j.Logger;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.FormContentFilter;
import org.springframework.web.servlet.DispatcherServlet;

public class Application implements WebApplicationInitializer {
	Logger log = org.slf4j.LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {

		XmlWebApplicationContext appContext = new XmlWebApplicationContext();

		appContext.setConfigLocation("classpath:/spring-*.xml");
		// 创建前端控制器
		ServletRegistration.Dynamic registration = servletContext.addServlet("dispatcher",
				new DispatcherServlet(appContext));
		registration.setLoadOnStartup(1);
		registration.addMapping("/");
		log.debug("注册前端控制器DispatcherServlet,映射url=/");
		// 添加字符编码过滤器
		FilterRegistration.Dynamic characterEncodingFilter = servletContext.addFilter("characterEncodingFilter",
				new CharacterEncodingFilter("utf-8", true, true));
		characterEncodingFilter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/api/*");

		// 添加请求方法过滤器
		FilterRegistration.Dynamic formContentFilter = servletContext.addFilter("formContentFilter",
				new FormContentFilter());
		formContentFilter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/api/*");
		log.debug("注册支持put/delete请求方法过滤器，映射URL:/api/*");
	}

//手动创建validator
	public Validator createValidator() {
		log.debug("注册快速失败特性的Validator");
		return Validation.byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory()
				.getValidator();
	}

}
